const path = require('path')
const fs = require('fs')
const express = require('express')
const ReactSSR = require('react-dom/server')
const serverEntry = require('./dist/server-entry').default
const port = 80
const app = express()
let indexContent

console.log(`环境信息：`)
console.log(`${__dirname}`)

fs.readFile(path.join(__dirname, 'dist', 'index.html'), 'utf8', (err, data) => {
    indexContent = data
});

app.get(`/*`, (req, res, next) => {
    if (req.url.endsWith('.js')
        || req.url.endsWith('.jpg')
        || req.url.endsWith('.png')
        || req.url.endsWith('.gif')
        || req.url.endsWith('.css')
        || req.url.match(/.*\.[mM][dD](\?[^\?]*)?/)) {
        next()
    } else {
        const content = ReactSSR.renderToString(serverEntry(req.url))
        const html = indexContent.replace('<!--content-->', content)
        res.send(html)
    }
})

app.get(/.*\.[mM][dD](\?[^\?]*)?/, (req, res, next) => {
    let idx = req.url.indexOf("?")
    let file
    if (idx < 0) {
        file = path.join(__dirname, 'dist', req.url)
    } else {
        file = path.join(__dirname, 'dist', req.url.substr(0, idx))
    }
    console.log(file)
    res.download(file)
})

app.get(`*.js`, (req, res, next) => {
    res.download(path.join(__dirname, 'dist', req.url))
})

app.get(`*.jpg`, (req, res, next) => {
    res.download(path.join(__dirname, 'dist', req.url))
})

app.get(`*.png`, (req, res, next) => {
    res.download(path.join(__dirname, 'dist', req.url))
})

app.get(`*.gif`, (req, res, next) => {
    res.download(path.join(__dirname, 'dist', req.url))
})

app.get(`*.css`, (req, res, next) => {
    res.download(path.join(__dirname, 'dist', req.url))
})

app.listen(port, function () {
    console.log(`成功的开启服务器在：${port}`)
})

function readDistContent(file, callback) {
    let filePath = path.join(__dirname, 'dist', file)
    fs.readFile(filePath, 'utf8', (err, data) => {
        callback(data)
    })
}